package com.ft.admix;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.ft.admix.ad.MixCustomRewardVideoAdapter;
import com.ft.admix.base.AdListener;
import com.ft.admix.base.BaseAd;
import com.ft.admix.base.ADMixAdapterIniter;
import com.ft.admix.config.AdClassConfig;
import com.ft.admix.config.AdConfig;
import com.ft.admix.config.PlatformConfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class AdManager {
    private static volatile AdManager instance;
    private Map<String, BaseAd> adCache = new HashMap<>();
    private Map<String, List<AdConfig>> waterfallConfigs = new HashMap<>(); // 瀑布流配置缓存

    // 瀑布流加载超时时间
    private static final long WATERFALL_TIMEOUT = 30_000; // 30秒
    // 单个广告位加载超时时间
    private static final long SINGLE_AD_TIMEOUT = 5_000;  // 5秒

    // 从后台获取配置并初始化
    public void initWithRemoteConfig(Context context) {
        // 从后台获取配置
        List<AdClassConfig> configs = fetchRemoteConfigs();


        // 注册广告平台
        for (AdClassConfig config : configs) {
            AdFactory.registerPlatform(config);
        }

        // TODO: 2025/3/11 请求获取平台sdk初始化参数
        // 初始化各平台SDK
//        for (PlatformConfig platformConfig : getPlatformConfigs()) {
//            initPlatformSDK(context, platformConfig);
//        }
    }

    private void loadRewardVideoAd(Activity activity, MixCustomRewardVideoAdapter ad,
                                   AdConfig config, AdListener listener) {
        // 获取瀑布流配置
        String waterfallKey = generateWaterfallKey(config);
        List<AdConfig> configs = waterfallConfigs.get(waterfallKey);

        if (configs == null) {
            // 首次加载，创建瀑布流配置
            // TODO: 2025/3/11 请求获取瀑布流配置
//            configs = createWaterfallConfigs(config);
            waterfallConfigs.put(waterfallKey, configs);
        }

        // 创建瀑布流加载器
        WaterfallLoader loader = new WaterfallLoader(activity, configs, listener);
        loader.startLoad();
    }

    private List<AdClassConfig> fetchRemoteConfigs() {
//        {
//            "platforms": [
//            {
//                "platformName": "CSJ",
//                    "initializerClass": "com.ad.sdk.platform.csj.CSJInitializer",
//                    "adClasses": {
//                        "SPLASH": "com.ad.sdk.platform.csj.CSJSplashAd",
//                        "REWARD_VIDEO": "com.ad.sdk.platform.csj.CSJRewardVideoAd",
//                        "INTERSTITIAL": "com.ad.sdk.platform.csj.CSJInterstitialAd",
//                        "BANNER": "com.ad.sdk.platform.csj.CSJBannerAd",
//                        "NATIVE": "com.ad.sdk.platform.csj.CSJNativeAd"
//                    }
//            },
//
//            ]
//        }
        return null;
    }

    private void initPlatformSDK(Context context, PlatformConfig config) {
        try {
            Object initializer = AdFactory.createPlatformInitializer(config.getPlatformName());
            if (initializer instanceof ADMixAdapterIniter) {
                ((ADMixAdapterIniter) initializer).initialize(context, config);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 加载广告
    public void loadAd(Activity activity, AdConfig adConfig, AdListener listener) {

    }

    // 瀑布流加载器
    private class WaterfallLoader {
        private final Activity activity;
        private final List<AdConfig> configs;
        private final AdListener originalListener;
        private final AtomicInteger currentIndex = new AtomicInteger(0);
        private final long startTime;
        private volatile boolean isLoading = false;
        private volatile boolean hasLoaded = false;

        public WaterfallLoader(Activity activity, List<AdConfig> configs, AdListener listener) {
            this.activity = activity;
            this.configs = configs;
            this.originalListener = listener;
            this.startTime = System.currentTimeMillis();
        }

        public void startLoad() {
            if (isLoading || hasLoaded) {
                return;
            }
            isLoading = true;
            loadNext();
        }

        private void loadNext() {
            // 检查是否超出总超时时间
            if (System.currentTimeMillis() - startTime > WATERFALL_TIMEOUT) {
                onWaterfallFailed("Waterfall timeout");
                return;
            }

            // 检查是否已尝试所有配置
            int index = currentIndex.get();
            if (index >= configs.size()) {
                onWaterfallFailed("All configurations failed");
                return;
            }

            AdConfig currentConfig = configs.get(index);
            BaseAd ad = AdFactory.createAd(currentConfig.getPlatformName(), currentConfig.getAdType());

            if (!(ad instanceof MixCustomRewardVideoAdapter)) {
                loadNext();
                return;
            }

//            MixCustomRewardVideoAdapter rewardAd = (MixCustomRewardVideoAdapter) ad;

            // 创建超时任务
            Handler timeoutHandler = new Handler(Looper.getMainLooper());
            Runnable timeoutRunnable = () -> {
                if (!hasLoaded) {
                    currentIndex.incrementAndGet();
                    loadNext();
                }
            };

            // 包装监听器
            AdListener wrapListener = new AdListener() {
                @Override
                public void onAdLoaded() {
                    if (hasLoaded) return;

                    hasLoaded = true;
                    timeoutHandler.removeCallbacks(timeoutRunnable);

                    // 缓存成功加载的广告
                    String key = generateKey(currentConfig);
                    adCache.put(key, ad);

                    if (originalListener != null) {
                        originalListener.onAdLoaded();
                    }
                }

                @Override
                public void onAdError(int code, String message) {
                    if (hasLoaded) return;

                    // 记录错误日志
                    logAdError(currentConfig, code, message);

                    // 尝试加载下一个配置
                    currentIndex.incrementAndGet();
                    loadNext();
                }

                // 其他回调方法转发给原始监听器
                @Override
                public void onAdShow() {
                    if (originalListener != null) originalListener.onAdShow();
                }

                @Override
                public void onAdClosed() {
                    String key = generateKey(currentConfig);
                    adCache.remove(key);
                    if (originalListener != null) originalListener.onAdClosed();
                }

                @Override
                public void onAdClicked() {
                    if (originalListener != null) originalListener.onAdClicked();
                }

                @Override
                public void onRewardVerify(boolean rewardVerify) {
                    if (originalListener != null) originalListener.onRewardVerify(rewardVerify);
                }
            };

            // 设置单个广告位加载超时
            timeoutHandler.postDelayed(timeoutRunnable, SINGLE_AD_TIMEOUT);

            // 开始加载广告
            try {
                activity.runOnUiThread(() -> {
                    try {
                        ad.setAdListener(wrapListener);
                        ad.load(
                                activity,
                                currentConfig);
                    } catch (Exception e) {
                        wrapListener.onAdError(-1, "Load ad exception: " + e.getMessage());
                    }
                });
            } catch (Exception e) {
                wrapListener.onAdError(-1, "Load ad exception: " + e.getMessage());
            }
        }

        private void onWaterfallFailed(String reason) {
            isLoading = false;
            if (originalListener != null && !hasLoaded) {
                originalListener.onAdError(-1, "Waterfall load failed: " + reason);
            }
        }
    }

    private String generateKey(AdConfig currentConfig) {
        return currentConfig.getAdId() + "_" + currentConfig.getPlatformName();
    }

    // 生成瀑布流配置的key
    private String generateWaterfallKey(AdConfig config) {
        return config.getAdType().name() + "_waterfall";
    }

    // 记录广告错误
    private void logAdError(AdConfig config, int code, String message) {
        // 实现错误日志记录逻辑
        Log.e("AdManager", String.format("Ad load failed - Platform: %s, Code: %d, Message: %s",
                config.getPlatformName(), code, message));
    }

}